package paim.wingchun.app;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;

import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hsqldb.ServerConstants;

public class Hibernates {

    private static SessionFactory sessionFactory;

    private static Configuration configuration = null;

    public Hibernates() throws HibernateException {
        this(Constantes.App$banco, Constantes.App$usuario, Constantes.App$senha);
    }

    public Hibernates(String db, String usuario, String senha) throws HibernateException {
        this(HyperSQLs.ipPadrao, db, Integer.toString(ServerConstants.SC_DEFAULT_HSQL_SERVER_PORT), usuario, senha,
                        false);
    }

    public Hibernates(String ip, String db, String portaTCP, String usuario, String senha, boolean create)
                    throws HibernateException {

        AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
        /* classes do wingchun sao adicionadas aqui mesmo, as outras no xml */
        annotationConfiguration.addAnnotatedClass(paim.wingchun.model.pojos.Erro.class);

        // Configuration config = new Configuration();
        // config.configure();
        Configuration config = annotationConfiguration.configure("/hibernate.cfg.xml");
        config.setProperty("hibernate.connection.driver_class", HyperSQLs.DRIVER);
        config.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        config.setProperty("hibernate.connection.url", HyperSQLs.url());

        config.setProperty("hibernate.connection.username", usuario);
        config.setProperty("hibernate.connection.password", senha);
        config.setProperty("hibernate.connection.port", portaTCP);

        if ( create )
            /* A value of create will create your tables at sessionFactory creation, and leave them intact. */
            config.setProperty("hibernate.hbm2ddl.auto", "create");
        else
            /* This is supposed to maintain the schema to follow any changes you make to the Model each time you run the
             * app. */
            config.setProperty("hibernate.hbm2ddl.auto", "update");

        /* Cria a fabrica */
        sessionFactory = config.buildSessionFactory();

        WC_Log.getInstancia().getlogger()
                        .log(Level.FINEST, WC_Strings.formataMap("Configuração hibernate", config.getProperties()));

        configuration = config;
    }

    /** @see {@link Configuration#buildSessionFactory}
     * @author temujin
     * @param password
     *            void */
    public static void atualizaFabrica(String password) {
        configuration.setProperty("hibernate.connection.password", password);
        sessionFactory = configuration.buildSessionFactory();
    }

    public static Session openSession() throws HibernateException {
        Session sessao = sessionFactory.openSession();
        sessao.setFlushMode(FlushMode.COMMIT);

        return sessao;
    }

    public static void close() {
        sessionFactory.close();
    }

    public static void execute(String sql) throws SQLException {
        Session session = sessionFactory.openSession();
        Connection connection = session.connection();
        Statement statement = connection.createStatement();
        statement.execute(sql);
    }

    public static void execute(Connection connection, String sql) throws SQLException {
        Statement statement = connection.createStatement();
        statement.execute(sql);
    }

    public static void shutdown() throws SQLException {
        execute("SHUTDOWN COMPACT");
    }

    public static void defrag() throws SQLException {
        execute("CHECKPOINT DEFRAG");
    }

    public static void defrag(Connection connection) throws SQLException {
        execute(connection, "CHECKPOINT DEFRAG");
    }

    public static void trocaSenha(Connection connection, String user, String pass) throws SQLException {
        StringBuilder s = new StringBuilder();
        s.append("ALTER USER ").append(user);
        s.append(" SET PASSWORD ").append("\"").append(pass).append("\"");

        PreparedStatement preparedStatement = connection.prepareStatement(s.toString());
        preparedStatement.execute();
    }

}
